﻿using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using System;

namespace OneLoginPlugin
{
    [Route("/SAMLLogin", "GET")]
    public class SAMLLogin
    {

    }
    
    public class SAMLLoginService : Service
    {
        public object Any(SAMLLogin request)
        {         
            string redirect = this.Request.QueryString["redirect"]; 

            if (string.IsNullOrEmpty(redirect))
            {
                redirect = this.Request.GetPathUrl();
            }                        

            AccountSettings accountSettings = new AccountSettings(new ServiceStack.Configuration.AppSettings(), redirect);

            AuthRequest req = new AuthRequest(accountSettings);

            string authRequest = req.GetRequest(AuthRequest.AuthRequestFormat.Base64);

            UriBuilder uriBuilder = new UriBuilder(accountSettings.idp_sso_target_url);
            uriBuilder.Query.AddQueryParam(SAMLAuthProvider.SAML_REQUEST, authRequest);
            uriBuilder.Query.AddQueryParam(SAMLAuthProvider.RELAY_STATE, redirect);

            return this.Redirect(uriBuilder.ToString());

        }
    }
}
